/**
 * 
 */
package hoan.com.test.service.persistence;

import hoan.com.test.model.Book;
import hoan.com.test.model.impl.BookImpl;

import java.util.ArrayList;
import java.util.List;

import com.liferay.portal.kernel.bean.PortalBeanLocatorUtil;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.SQLQuery;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.dao.orm.SessionFactory;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
import com.liferay.util.dao.orm.CustomSQLUtil;

/**
 * @author Horizon
 * 
 */
public class BookFinderImpl extends BasePersistenceImpl<Book> implements
		BookFinder {

	@SuppressWarnings("unchecked")
	public List<Book> findAllBooksByUserId(long userId) {

		List<Book> bookList = new ArrayList<Book>();
		String queryId = "getAllBooksByUserIdCustomSQLId";
//		SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");
		
		Session session = null;
        String sql = null;
        try
        {
//            session = sessionFactory.openSession();
            session = openSession();
            if (Validator.isNotNull(userId))
            {
                sql = CustomSQLUtil.get(queryId);
            } 
            SQLQuery query = session.createSQLQuery(sql);
            query.addEntity("Book", BookImpl.class);
            QueryPos qPos = QueryPos.getInstance(query);
            qPos.add(userId);

            bookList = (List<Book>) query.list();
        } catch (Exception e){
            e.printStackTrace();
        } finally{
//        	sessionFactory.closeSession(session);
        	closeSession(session);
        }

		return bookList;
	}
}
